package cn.iocoder.yudao.module.book.controller.app.upload;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.module.book.service.audio.AudioService;
import cn.iocoder.yudao.module.book.service.minio.MinioService;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

@RestController
@RequestMapping("/api/user")
public class MinioUploadController {
    
    @Resource
    private MinioService minioService;

    @Resource
    private AudioService auidoService;
    
    // 获取预签名URL（替代 getDirectUploadToken）
    @GetMapping("/upload/getDirectUploadToken")
    @Operation(summary = "获取预签名URL")
    public CommonResult<String> getPresignedUrl(@RequestParam String fileName) {
        try {
            String url = minioService.getPresignedUploadUrl(fileName);
            return CommonResult.success(url);
        } catch (Exception e) {
            return CommonResult.error(500,"生成上传链接失败");
        }
    }
    
    // 上传录音（二进制直接入库，不走 MinIO）
    @PostMapping("/recording/upload")
    @Operation(summary = "上传录音数据到数据库")
    public CommonResult<Boolean> uploadRecording(
            @RequestParam Long bookId,
            @RequestParam Integer page,
            @RequestParam MultipartFile audio) {
        try {
            byte[] data = audio.getBytes();
            String contentType = audio.getContentType();
            auidoService.saveRecordingData(bookId, page, data, contentType);
            return CommonResult.success(Boolean.TRUE);
        } catch (Exception e) {
            return CommonResult.error(500, "上传录音失败：" + e.getMessage());
        }
    }
//    @PostMapping("/recording/upload")
//    @Operation(summary = "上传录音到 MinIO")
//    public CommonResult uploadRecording(
//            @RequestParam Long bookId,
//            @RequestParam Integer page,
//            @RequestParam MultipartFile audio) {
//
//        try {
//            // 构造对象名（ObjectName），例如：book_{bookId}_page_{page}.wav
//            String objectName = String.format("book_%d_page_%d%s",
//                    bookId, page,
//                    audio.getOriginalFilename().substring(audio.getOriginalFilename().lastIndexOf(".")));
//
//            // 调用 MinIO 服务上传文件
//            minioService.uploadFile(
//                    objectName,
//                    audio.getInputStream(),
//                    audio.getSize(),
//                    audio.getContentType()
//            );
//
//            // 返回成功
//            return CommonResult.success(objectName);
//        } catch (Exception e) {
//            return CommonResult.error(500, "上传录音失败：" + e.getMessage());
//        }
//    }

}